package com.zhentao.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zhentao.pojo.HospitalNavigation;
import com.zhentao.pojo.R;
import com.zhentao.service.HospitalNavigationService;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@RequestMapping("/hospital-nav")
public class HospitalNavigationController {

    @Autowired
    private HospitalNavigationService hospitalNavigationService;

    // 列表：启用状态，按sort升序
    @GetMapping("/list")
    public R<List<HospitalNavigation>> list() {
        log.info("接收到医院导航列表请求");
        try {
            List<HospitalNavigation> list = hospitalNavigationService.list(
                new LambdaQueryWrapper<HospitalNavigation>()
                    .eq(HospitalNavigation::getStatus, 1)
                    .orderByAsc(HospitalNavigation::getSort)
            );
            log.info("查询到{}条医院导航数据", list.size());
            return R.ok(list);
        } catch (Exception e) {
            log.error("查询医院导航列表失败", e);
            return R.failed("查询失败：" + e.getMessage());
        }
    }

    // 详情：按院区名称或院区编码查询
    @GetMapping("/detail/{key}")
    public R<HospitalNavigation> detail(@PathVariable("key") String key) {
        log.info("接收到医院导航详情请求，key: {}", key);
        if (!StringUtils.hasText(key)) {
            return R.failed("参数不能为空");
        }
        try {
            HospitalNavigation one = hospitalNavigationService.getOne(
                new LambdaQueryWrapper<HospitalNavigation>()
                    .and(w -> w.eq(HospitalNavigation::getHospitalArea, key)
                               .or()
                               .eq(HospitalNavigation::getBranchCode, key))
                    .last("limit 1")
            );
            if (Objects.isNull(one)) {
                return R.failed("未找到对应院区");
            }
            return R.ok(one);
        } catch (Exception e) {
            log.error("查询医院导航详情失败", e);
            return R.failed("查询失败：" + e.getMessage());
        }
    }

    // 地图key（小程序端可先请求拿到key，或写死在前端）
    @GetMapping("/map-key")
    public R<String> mapKey() {
        log.info("接收到地图key请求");
        return R.ok("CHWBZ-JY7K3-OB43E-O7WXM-XGLJK-CPFYN");
    }
}


